package com.xiaomi.front.controller;

import com.xiaomi.front.service.user.UserService;
import com.xiaomi.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;


@Controller
public class UserController {

    @Autowired
    private UserService userService;


    /*
    实现登陆
    如果user值为null，
    登陆页提示错误
    否则 进入首页
    记录最新登陆时间
     */
    @PostMapping("/login_front")
    public String IfLogin(String number, String password, String code, HttpSession session) {
        //获取session中得验证码
        String code_key = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        //移除session验证码
        session.removeAttribute(KAPTCHA_SESSION_KEY);
        //与接收验证码比较
        if (code.equals(code_key)) {
            User user = userService.Login(number, password);
            if (user == null) {
                String err = "账户或密码不正确！";
                session.setAttribute("err", err);
                return "forward:/front_login.jsp";
            } else {
                int frozen = user.getFrozen();
                if (frozen == 0) {
                    userService.LoginTime(user.getUid());
                    session.setAttribute("user", user);
                    return "front/index";
                } else {
                    session.setAttribute("err", "账户被冻结,禁止登陆!");
                    return "forward:/front_login.jsp";
                }

            }
        } else {
            session.setAttribute("err", "验证码不正确！");
            return "forward:/front_login.jsp";
        }
    }

    //用户退出
    @RequestMapping("/Front_out")
    public String Close(HttpSession session) {
        //移除指定session 是页面其他session存在
        session.removeAttribute("user");
        return "front/index";
    }
}
